import { reactive, ref, watch } from "vue"
import GradeTarget from "~/api/apis/grade"
import { SpiAxios } from "@service/spi/spi"
import Storage from "@service/storage/storage"
import CourseTarget from "~/api/apis/course"
import RemarkTarget from "~/api/apis/remark";
import { ElMessage } from "element-plus";
import RecordTarget from "~/api/apis/record";
import { ElLoading } from 'element-plus'

import type { TreeInstance } from 'element-plus'

class Record {
    public content!: string;
    public courseId!: number;
    public courseName!: string;
    public studentId!: number;
}
const level = ref('')
const treeRef = ref<TreeInstance>()
const students = ref<any[]>([])
const course_content = ref<any>()

const course = ref<number>()
let form = [] as any;

interface Tree {
    id: number,
    name: string,

}const selectCourse = (val: number) => {
    course.value = val;
    console.log(course.value);
    getContents(val);

};
const handleChange = (val: any) => {
    course_content.value = val;
    getRemarkList(val.id);
}
const insert = () => {
    if (course.value == undefined || course.value == 0) {
        ElMessage.error("请选择课程");
        return;
    }
    if (students.value.length == 0) {
        ElMessage.error("请勾选学生");
        return;
    }
    if (course_content.value == undefined) {
        ElMessage.error("请选择课程内容");
        return;
    }
    if (remarks.data.length == 0) {
        ElMessage.error("当前课程没有评价模板");
        return;
    }
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    form = [];
    students.value.map(student => {
        convert_record(student);
        form.push(convert_record(student));
    });
    console.log(form);
    SpiAxios.create(RecordTarget.inserts(form))
        .http()
        .then(data => {
            loading.close();
            ElMessage.success("添加成功");

        })
        .catch(err => {
            loading.close();
            ElMessage.error(err.msg);
            console.log(err);
        });
};
/** 模板数据 */
const common_moulds = reactive({
    start_moulds: [] as any,
    content_moulds: [] as any,
    behavior_moulds: [] as any,
    specific_moulds: [] as any,
    end_moulds: [] as any
});
const convert_form = (students: any[]) => {

};
const convert_record = (student: any) => {
    let form = new Record();
    form.studentId = student.id;
    form.courseId = course.value!;
    form.courseName = form.courseName = courses.data.filter((e: any) => {
        return e.id == form.courseId;
    })[0].name;
    let preview = "";
    let start_mould = getElement(common_moulds.start_moulds).content;
    let content_mould = course_content.value.content;
    let end_mould = getElement(common_moulds.end_moulds).content;
    let behavior_mould = getElement(remarks.data).content;
    preview += "<P>&nbsp; &nbsp; &nbsp; &nbsp;" + start_mould + "</p>";
    preview += "<P>&nbsp; &nbsp; &nbsp; &nbsp;" + content_mould + "</p>";
    preview += "<p>&nbsp; &nbsp; &nbsp; &nbsp;" + behavior_mould + "</p>";
    preview += "<p>&nbsp; &nbsp; &nbsp; &nbsp;" + end_mould;

    form.content = preview.replaceAll("[NAME]", student.name).replaceAll("[COURSE]", form.courseName);
    return form;
};
const getElement = (arr: any[]) => {
    if (arr.length === 0) {
        return undefined;
    }
    // 为了避免修改原数组，可以先复制一份再打乱
    const shuffledArray = shuffleArray(arr.slice());
    return shuffledArray[0]; // 返回打乱后的第一个元素
}
const shuffleArray = (arr: any[]) => {
    for (let i = arr.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [arr[i], arr[j]] = [arr[j], arr[i]]; // 交换元素
    }
    return arr;
}

/** 班级数据 */
const tree = reactive({
    data: [] as Tree[],
})
const getTree = () => {
    const user = Storage.get('user')
    SpiAxios
        .create(GradeTarget.tree({ id: user.id }))
        .http()
        .then((data) => {
            let list = data.map((item: { id: number, name: string, students: any }) => {
                return {
                    id: item.id,
                    name: item.name.slice(0, 8),
                    disabled: true,
                    children: item.students.map((student: { id: number, name: string }) => {
                        return {
                            id: student.id,
                            name: student.name,
                        }
                    }),
                }
            })
            console.log(list)
            tree.data = list

        })
        .catch((err) => {
            console.log(err)
        })
}
/** 课程主题模板 */
const courses = reactive({
    data: [] as any,
})
const getCourseList = () => {
    SpiAxios
        .create(CourseTarget.courses({ "level": level.value }))
        .http()
        .then((data) => {
            console.log(data)
            courses.data = data
        })
        .catch((err) => {
            console.log(err)
        })
}
/** 课程评价 */
const remarks = reactive({
    data: [] as any[]
});
const getRemarkList = (id: number) => {
    SpiAxios.create(RemarkTarget.remarksByMould({ id: id }))
        .http()
        .then(data => {
            console.log(data);
            remarks.data = data;
        })
        .catch(err => {
            console.log(err);
        });
};
const course_contents = reactive({
    data: [] as any,
})
const getContents = (id: number) => {
    SpiAxios
        .create(CourseTarget.moulds({ id: id }))
        .http()
        .then((data) => {
            console.log(data)
            course_contents.data = data.moulds
        })
        .catch((err) => {
            console.log(err)
        })
}
/** 模板数据 */
const moulds = reactive({
    grade: {},
    data: [] as any,
})
const getMouldsList = () => {
    SpiAxios
        .create(CourseTarget.moulds({ id: 1 }))
        .http()
        .then((data) => {
            console.log(data)
            common_moulds.start_moulds = data.moulds.filter((e: { type: number }) => {
                return e.type == 1;
            })
            common_moulds.end_moulds = data.moulds.filter((e: { type: number }) => {
                return e.type == 4;
            });
        })
        .catch((err) => {
            console.log(err)
        })
}
getMouldsList();
const getLevel = (level: string) => {
    switch (level) {
        case "3":
            return "F1"
        case "4":
            return "F2"
        case "5":
            return "F3"
        case "6":
            return "F4"
        case "7":
            return "F5"
        case "8":
            return "S1"
        case "9":
            return "S2"
        case "10":
            return "Scratch"
        case "11":
            return "木编"
        case "12":
            return "Python"
        case "13":
            return "Python+机器人"
        default:
            break;
    }
}
export {
    Tree,
    tree,
    getTree,
    level,
    course,
    courses,
    getCourseList,
    selectCourse,
    remarks,
    course_contents,
    handleChange,
    moulds,
    getMouldsList,
    treeRef,
    students,
    insert
}